package com.hornsun.data.repository;


import com.hornsun.data.dbo.Authorization;
import com.hornsun.data.dbo.AuthorizationExample;
import com.hornsun.data.repository.mapper.AuthorizationMapper;
import com.hornsun.util.LittleUtil;
import com.hornsun.util.StrUtil;
import org.assertj.core.util.Preconditions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 * Created by 编译中... on 2018/6/15.
 */
@Repository
public class AuthorizationRepository {
    @Autowired
    private AuthorizationMapper authorizationMapper;

    public int getTotalCount(){
        return (int)authorizationMapper.countByExample(new AuthorizationExample());
    }

    public List<Authorization> getAuthInfo(int page){
        AuthorizationExample authorizationExample = new AuthorizationExample();
        authorizationExample.setOrderByClause(StrUtil.toDesc("time"));
        return authorizationMapper.selectByExampleWithRowbounds(authorizationExample, LittleUtil.rowBounds(page,8));
    }

    public void add(Authorization authorization){
        if (authorizationMapper.insertSelective(authorization)!=1){
            throw new IllegalArgumentException("insert authorization failed ");
        }
    }

    public void delete(String guid){
        Preconditions.checkNotNull(guid);
        int count = authorizationMapper.deleteByPrimaryKey(guid);
        if (count!=1){
            throw new IllegalArgumentException("delete authorization failed by guid:"+guid);
        }
    }

    public void updateOfflineTime(Authorization authorization){
        Preconditions.checkNotNull(authorization);
        Preconditions.checkNotNull(authorization.getClientGuid());
        if (authorizationMapper.updateByPrimaryKeySelective(authorization)!=1){
            throw new IllegalArgumentException("update authorization failed by authorization"+authorization);
        }
    }

    public Authorization getByGuid(String guid){
        Preconditions.checkNotNull(guid);
        return authorizationMapper.selectByPrimaryKey(guid);
    }

    public boolean hasRecord(String clientGuid){
        AuthorizationExample authorizationExample = new AuthorizationExample();
        AuthorizationExample.Criteria criteria = authorizationExample.createCriteria();
        criteria.andClientGuidEqualTo(clientGuid);
        return authorizationMapper.countByExample(authorizationExample)==1;
    }

    public boolean whetherAuthByName(String name){
        return authorizationMapper.countByUserName(name)==1;
    }

    public Authorization getByName(String name){
        return authorizationMapper.getByUserName(name);
    }
}
